package com.vtc.session16;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class DownloadUtil extends AsyncTask<String, Integer, String>{

	private ProgressDialog prog;
	
	public DownloadUtil(Context context){
		prog = new ProgressDialog(context);
		prog.setMessage("Downloading file...");
		prog.setMax(100);
		prog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	}
	@Override
	protected String doInBackground(String... params) {		
		try {
			// step 1: connect to resource
			URL url = new URL(params[0]);
			URLConnection conn = url.openConnection();
			conn.connect();
			// step 2: create inputstream and read data, write to file
			InputStream iStream = new BufferedInputStream(conn.getInputStream());
			OutputStream oStream= new FileOutputStream(params[1]);
			int total = conn.getContentLength(); // kich thuoc file
			int curTotal=0; // tong so byte download duoc
			
			int count = 0; // so byte down duoc moi lan doc
			byte[] b = new byte[1024];
			while((count=iStream.read(b))!=-1){
				curTotal = curTotal +count; 
				oStream.write(b,0,count);
				publishProgress(curTotal*100/total);
			}
			// step 3: close all connection
			iStream.close();
			oStream.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	@Override
	protected void onPreExecute() {	
		super.onPreExecute();
		prog.show();
	}
	@Override
	protected void onProgressUpdate(Integer... values) {	
		super.onProgressUpdate(values);
		prog.setProgress(values[0]);
	}
	@Override
	protected void onPostExecute(String result) {	
		super.onPostExecute(result);
		prog.dismiss();
	}

}
